package com.jdy.haoduoaiteacher.scan.decode;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.Hashtable;

/**
 * 
 * @author hufei
 * 
 */
public class Bitmap2QR {
  private final static int TARGET_HEIGHT = 200;
  private final static int TARGET_WIDTH = 200;

  private static final int BUFFER_SIZE = 1024;

  public static Result scanningImage(InputStream is) {
    if (is == null) {
      return null;
    }
    try {
      Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
      hints.put(DecodeHintType.CHARACTER_SET, "UTF8");

      Options options = new Options();
      options.inJustDecodeBounds = true;

      if (!is.markSupported()) {
        is = new BufferedInputStream(is);
      }
      is.mark(BUFFER_SIZE);
      BitmapFactory.decodeStream(is, null, options);

      Boolean scaleByHeight = Math.abs(options.outHeight - TARGET_HEIGHT) >= Math
          .abs(options.outWidth - TARGET_WIDTH);
      if (options.outHeight * options.outWidth * 2 >= TARGET_HEIGHT
          * TARGET_WIDTH * 2) {

        double sampleSize = scaleByHeight ? options.outHeight / TARGET_HEIGHT
            : options.outWidth / TARGET_WIDTH;
        options.inSampleSize = (int) Math.pow(2d,
            Math.floor(Math.log(sampleSize) / Math.log(2d)));
      }
      options.inJustDecodeBounds = false;
      is.reset();
      Bitmap scanBitmap = BitmapFactory.decodeStream(is, null, options);
      RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
      is.close();
      BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
      QRCodeReader reader = new QRCodeReader();

      return reader.decode(bitmap1, hints);

    } catch (Exception e) {
      e.printStackTrace();
    } catch (Error e) {
      e.printStackTrace();
    }
    return null;
  }
}
